package com.healthchart.app.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.healthchart.app.R;
import com.healthchart.app.bean.WeightBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import androidx.fragment.app.Fragment;

public class BodyFragment extends Fragment implements OnChartValueSelectedListener {
    private String tag="BodyFragment";
    View mView=null;
    private LineChart chart;
    private LineData data = null;
    //数据线
    private ILineDataSet set = null;
    //右边延长线
    private ILineDataSet setRightTemp = null;
    //左边延长线
    private ILineDataSet setLeftTemp = null;
    private TextView tvmid;
    private XAxis xl;
    private Legend legend;
    private Entry midentry,mixentry;
    //计时器
    private Timer timer = null;
    private TimerTask timerTask = null;
    //X轴日期数据
    private List<String> list = new ArrayList<String>();
    //坐标轴尺寸
    private float width=0;
    private float height=0;
    //数据列表
    private List<WeightBean> weightBeanList = new ArrayList<WeightBean>();
    boolean flag=false;
    //表情
    private ImageView ivs1,ivs2,ivs3;
    ViewTreeObserver vto;
    boolean isMeasured = false;
    int page = 0;

    private void chartConfig()
    {
        chart.setOnChartValueSelectedListener(this);
        chart.setViewPortOffsets(0, 25, 0, 50);
        Description description = new Description();
        description.setText("健康管理");
        description.setTextSize(15f);
        description.setXOffset(10f);
        chart.setDescription(description);
        chart.getDescription().setEnabled(false);

        // 获取图例(即左下角中各个图形的标识)
        legend = chart.getLegend();
        // 设置图例文字颜色
        legend.setTextColor(getResources().getColor(R.color.white));
        // 设置图例文字大小
        legend.setTextSize(20);
        // 设置图例位置：水平居中
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        // 设置图例样式(默认是小方格)
        legend.setForm(Legend.LegendForm.NONE);
        // 设置图例大小
        legend.setFormSize(15);
        // enable touch gestures
        chart.setTouchEnabled(true);
        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setPinchZoom(true);
        // background color
        chart.setBackgroundColor(getResources().getColor(R.color.blue));
        //设置是否显示表格背景
        chart.setDrawGridBackground(false);
        //Y轴禁用
        chart.getAxisLeft().setEnabled(false);
        chart.getAxisRight().setEnabled(false);
        //设置chart是否可以触摸
        chart.setTouchEnabled(true);
        //设置是否可以拖拽
        chart.setDragEnabled(true);
        //设置是否可以缩放 x和y
        chart.setScaleEnabled(false);
        //是否缩放X轴
        chart.setScaleXEnabled(false);
        //是否缩放Y轴
        chart.setScaleYEnabled(false);
        //设置是否可以通过双击屏幕放大图表。
        chart.setDoubleTapToZoomEnabled(false);

        chart.setOnChartGestureListener(new OnChartGestureListener() {
            @Override
            public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
            }

            @Override
            public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                if (flag) {
                    return;
                }
                Highlight h = chart.getHighlightByTouchPoint(0, height / 2);
                if (h == null) {
                    return;
                }
                else
                {
                    mixentry = chart.highlightValuePoint(h);
                }
                if (set.getEntryCount() >=100) {
                    addLList();
                    flag = true;
                    return;
                }
                //向左滑动且已经是最边沿才加载数据
                if(me.getEdgeFlags()>0 && mixentry.getX()==data.getXMin() && lastPerformedGesture.name().equals("DRAG"))
                {
                    page++;
                    for (int i = 0; i < 10; i++) {
                        chart.clearValues();
                        WeightBean weightBean = new WeightBean();
                        weightBean.setDate(page+"-"+i);
                        weightBean.setWeight((float) (Math.random() * 40) + 30f);
                        weightBeanList.add(i,weightBean);
                    }
                    addList(weightBeanList);
                    addRList();
                }
            }

            @Override
            public void onChartLongPressed(MotionEvent me) {
            }

            @Override
            public void onChartDoubleTapped(MotionEvent me) {
            }

            @Override
            public void onChartSingleTapped(MotionEvent me) {
            }

            @Override
            public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {
            }

            @Override
            public void onChartScale(MotionEvent me, float scaleX, float scaleY) {
            }

            @Override
            public void onChartTranslate(MotionEvent me, float dX, float dY) {
            }
        });

        LineData data = new LineData();
        data.setValueTextColor(Color.WHITE);
        // add empty data
        chart.setData(data);
        //x坐标轴
        xl = chart.getXAxis();
        xl.setTextColor(getResources().getColor(R.color.white));
        xl.setTextSize(15f);
        xl.setDrawGridLines(false);
        xl.setEnabled(true);
        //设置X轴的颜色
        xl.setAxisLineColor(getResources().getColor(R.color.white));
        //设置X轴的宽度
        xl.setAxisLineWidth(2f);
        //设置为true当一个页面显示条目过多，X轴值隔一个显示一个
        xl.setGranularityEnabled(true);
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置X轴避免图表或屏幕的边缘的第一个和最后一个轴中的标签条目被裁剪
        xl.setAvoidFirstLastClipping(true);

        //y坐标轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setTextColor(Color.WHITE);
        leftAxis.setAxisMaximum(100f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(true);
        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        for (int i = 0; i < 10; i++) {
            WeightBean weightBean = new WeightBean();
            weightBean.setDate(page+"-"+i);
            weightBean.setWeight((float) (Math.random() * 40) + 30f);
            weightBeanList.add(weightBean);
        }
        addList(weightBeanList);
        addRList();
        chart.moveViewToX(set.getEntryCount());
        midListen();
    }

    private void drawExpression(float value) {
//        if(value<100)
//        {
//            ivs1.setVisibility(View.VISIBLE);
//        }
//        else  if(value>=100 && value<=200 )
//        {
//            ivs2.setVisibility(View.VISIBLE);
//        }
//        else
//        {
//            ivs3.setVisibility(View.VISIBLE);
//        }
        ivs1.setVisibility(View.VISIBLE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_body, null);

        ivs1 = mView.findViewById(R.id.ivs1);
        ivs2 = mView.findViewById(R.id.ivs2);
        ivs3 = mView.findViewById(R.id.ivs3);

        tvmid = mView.findViewById(R.id.tvmid);
        chart = mView.findViewById(R.id.chart1);
        chartConfig();

        vto = mView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (!isMeasured) {
                    width = chart.getWidth();
                    height = chart.getHeight();
                    isMeasured = true;
                }
            }
        });
        return mView;
    }

    //增加数据
    private void addList(List<WeightBean> list) {
        this.list.clear();
        for (int i = 0; i < list.size(); i++) {
            addEntry(list.get(i));
        }
        chart.notifyDataSetChanged();
        chart.setVisibleXRangeMaximum(6);
    }

    private void addRList() {
        //目前添加3个 这个动态调整
        for (int i = weightBeanList.size(); i < weightBeanList.size()+3; i++) {
            WeightBean weightBean = new WeightBean();
            weightBean.setWeight(50);
            weightBean.setDate("");
            weightBean.setValue(i);
            addEntryRightTemp(weightBean);
        }
        chart.notifyDataSetChanged();
        chart.setVisibleXRangeMaximum(6);
    }

    private void addLList() {
        for (int i = -3; i < 0; i++) {
            WeightBean weightBean = new WeightBean();
            weightBean.setWeight(50);
            weightBean.setDate("");
            weightBean.setValue(i);
            addEntryLeftTemp(weightBean);
        }
        chart.notifyDataSetChanged();
        chart.setVisibleXRangeMaximum(6);
    }

    //增加数据
    private void addEntry(WeightBean wb) {
        data = chart.getData();
        if (data != null) {
            set = data.getDataSetByIndex(0);
            if (set == null) {
                set = createSet();
                data.addDataSet(set);
            }
            data.addEntry(new Entry(set.getEntryCount(), wb.getWeight()), 0);
            IndexAxisValueFormatter indexAxisValueFormatter = new IndexAxisValueFormatter();
            list.add(wb.getDate());
            String[] strings = new String[list.size()];
            list.toArray(strings);
            indexAxisValueFormatter.setValues(strings);
            xl.setValueFormatter(indexAxisValueFormatter);
        }
    }

    //增加右延长线
    private void addEntryRightTemp(WeightBean wb) {
        data = chart.getData();
        if (data != null) {
            setRightTemp = data.getDataSetByIndex(1);
            if (setRightTemp == null) {
                setRightTemp = createSetRightTemp();
                data.addDataSet(setRightTemp);
            }
            data.addEntry(new Entry(wb.getValue(), 50), 1);
        }
    }

    //增加左延长线
    private void addEntryLeftTemp(WeightBean wb) {
        data = chart.getData();
        if (data != null) {
            setLeftTemp = data.getDataSetByIndex(2);
            if (setLeftTemp == null) {
                setLeftTemp = createSetLeftTemp();
                data.addDataSet(setLeftTemp);
            }
            data.addEntry(new Entry(wb.getValue(), 50), 2);
        }
    }

    //创建数据源
    private LineDataSet createSet() {
        LineDataSet set = new LineDataSet(null, "kg");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setFillAlpha(65);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.rgb(244, 117, 117));
        //显示数值
        set.setDrawValues(false);
        //显示点
        set.setDrawCircles(true);
        // 点和线的颜色
        set.setColor(Color.WHITE);
        set.setCircleColor(Color.WHITE);
        set.setLineWidth(3f);
        set.setCircleRadius(5f);
        set.setCircleHoleRadius(5f);
        set.setValueTextSize(15f);
        set.setValueTextColor(getResources().getColor(R.color.white));
        // 绘制空心圆
        set.setDrawCircleHole(false);
        //画弧型
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        //是否填充颜色
        set.setDrawFilled(false);
        //是否显示选中线
        set.setDrawVerticalHighlightIndicator(false);
        set.setDrawHorizontalHighlightIndicator(false);
        return set;
    }

    private LineDataSet createSetRightTemp() {
        LineDataSet set = new LineDataSet(null, "");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setFillAlpha(65);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.rgb(244, 117, 117));
        set.setDrawValues(false);
        set.setDrawCircles(true);
        set.setColor(getResources().getColor(R.color.blue));
        set.setCircleColor(getResources().getColor(R.color.blue));
        set.setLineWidth(3f);
        set.setCircleRadius(5f);
        set.setCircleHoleRadius(5f);
        set.setValueTextSize(15f);
        set.setValueTextColor(getResources().getColor(R.color.white));
        set.setDrawCircleHole(false);
        set.setDrawFilled(false);
        set.setDrawVerticalHighlightIndicator(false);
        set.setDrawHorizontalHighlightIndicator(false);
        return set;
    }

    private LineDataSet createSetLeftTemp() {
        LineDataSet set = new LineDataSet(null, "");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setFillAlpha(65);
        set.setFillColor(ColorTemplate.getHoloBlue());
        set.setHighLightColor(Color.rgb(244, 117, 117));
        set.setDrawValues(false);
        set.setDrawCircles(true);
        set.setColor(getResources().getColor(R.color.blue));
        set.setCircleColor(getResources().getColor(R.color.blue));
        set.setLineWidth(3f);
        set.setCircleRadius(5f);
        set.setCircleHoleRadius(5f);
        set.setValueTextSize(15f);
        set.setValueTextColor(getResources().getColor(R.color.white));
        set.setDrawCircleHole(false);
        set.setDrawFilled(false);
        set.setDrawVerticalHighlightIndicator(false);
        set.setDrawHorizontalHighlightIndicator(false);
        return set;
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        //Log.e(tag, e.toString());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(timer!=null)
        {
            timer.cancel();
            timer=null;
            timerTask.cancel();
            timerTask=null;
        }
    }

    private void midListen() {
        timer=new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    Highlight h = chart.getHighlightByTouchPoint(width/2, height/2);
                    if (h!=null)
                    {
                        midentry = chart.highlightValuePoint(h);
                        handler.sendEmptyMessage(0);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
        timer.schedule(timerTask,1000,200);
    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 0:
                    tvmid.setText(midentry.getY()+"");
                    drawExpression(midentry.getY());
                    chart.centerViewTo(midentry.getX(), midentry.getY(), null);
                    break;
            }
        }
    };
}
